package cn.com.ursaminor.mysql4j.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 该类定义若干工具方法.
 * 
 * @author 小熊
 * @version 1.0
 */
public class Mysql4jUtil
{
	private static final SimpleDateFormat DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final SimpleDateFormat DATE = new SimpleDateFormat("yyyy-MM-dd");
	
	public static String formatDate(Date date)
	{
		if(date==null) return null;
		return DATETIME.format(date);
	}
	
	public static Date parseDate(String date)
	{
		if(date==null) return null;
		try
		{
			if(date.length()>19) date = date.substring(0,19);
			if(date.length()==10) return DATE.parse(date);
			else if(date.length()==19) return DATETIME.parse(date);
			else return null;
		}
		catch(ParseException e)
		{
			System.out.println(e);
			return null;
		}
	}
	
	public static String initialUpperCase(String str)
	{
		if(str==null || str.length()==0) return str;
		else return str.substring(0,1).toUpperCase()+str.substring(1);
	}
	
	public static Integer getInteger(Object s,Integer defaultValue)
	{
		try{
			if(s==null) return defaultValue;
			else return Integer.valueOf(s.toString());
		}catch(Exception e){
			return defaultValue;
		}
	}
	
	public static Long getLong(Object s,Long defaultValue)
	{
		try{
			if(s==null) return defaultValue;
			else return Long.valueOf(s.toString());
		}catch(Exception e){
			return defaultValue;
		}
	}
	
	public static Float getFloat(Object s,Float defaultValue)
	{
		try{
			if(s==null) return defaultValue;
			else return Float.valueOf(s.toString());
		}catch(Exception e){
			return defaultValue;
		}
	}
	
	public static Double getDouble(Object s,Double defaultValue)
	{
		try{
			if(s==null) return defaultValue;
			else return Double.valueOf(s.toString());
		}catch(Exception e){
			return defaultValue;
		}
	}
	
	public static Boolean getBoolean(Object s,Boolean defaultValue)
	{
		try{
			if(s==null) return defaultValue;
			else
			{
				return Mysql4jUtil.isTrue(s);
			}
		}catch(Exception e){
			return defaultValue;
		}
	}
	
	public static boolean isTrue(Object s)
	{
		if(s==null) return false;
		String ss = s.toString();
		return ss.equalsIgnoreCase("yes") || ss.equalsIgnoreCase("true") || ss.equalsIgnoreCase("on") || ss.equals("1") || ss.equals("是");
	}
	
	public static boolean isEmpty(String str)
	{
		return str==null || str.trim().length()==0;
	}
	
	public static boolean notEmpty(String str)
	{
		return !isEmpty(str);
	}
}
